<template>
  <div>
    <el-card>
      <el-row type="flex" justify="space-between">
        <el-button type="primary" size="small" @click="addFn">添加页面</el-button>
        <!-- 输入框 -->
        <el-row type="flex">
          <el-input v-model="input" placeholder="请输入内容" style="width: 500px;" />
          <el-button @click="screen">筛选</el-button>
        </el-row>
      </el-row>
      <el-divider />
      <!-- 表格 -->
      <el-table
        :data="pagesList"
        border
        style="width: 100%;margin:20px 0"
      >
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="content" label="内容">
          <template #default="{row}">
            <span v-html="row.content" />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="pageCompile(row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="delPages(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 直线 -->
      <el-divider />
      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <div class="block">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pagesSetting._limit"
            :current-page="currentPage"
            @current-change="currentChange"
          />
        </div>
      </el-row>
    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog :title="formData.id?'编辑页面':'新增页面'" :visible="isShowCompile" @close="btnCancelCompile">
      <el-form ref="Compile" label-width="80px" :model="formData" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>
        <!-- 富文本 -->
        <el-form-item label="内容" prop="content">
          <VueEditor ref="vueEditor" :config="config" />
        </el-form-item>
      </el-form>
      <!-- 两个按钮 -->
      <template #footer>
        <el-button size="small" type="primary" @click="btnCompileOk">确定</el-button>
        <el-button size="small" @click="btnCancelCompile">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 引入列表接口
import { getPagesList,
  addPages,
  delPages,
  getPagesQuantity,
  getCompile,
  addCompile
} from '@/api/pages'
// 引入富文本
import VueEditor from 'vue-word-editor'
import 'quill/dist/quill.snow.css'

export default {
  // 注册
  components: {
    VueEditor
  },
  data() {
    return {
      XMuData: [], // 要进行模糊搜索的数组
      // 筛选的输入框内容
      input: '',
      pagesSetting: {
        _start: 0, // 开始获取的位置
        _limit: 3 // 最大条数
      },
      total: 0, // 总条数
      currentPage: 0, // 最新的页面
      pagesList: [], // 列表数据
      isShowDialog: false, // 控制弹窗
      formData: {
        title: '', // 标题
        content: ''// 内容
      },
      userId: '',
      config: {
        // / 上传图片的配置
        uploadImage: {
          url: 'http://localhost:3000/upload', // 文章上传到服务器端的处理路径
          name: 'file', // 后台所需要的参数的名称
          // headers: this.getToken(), // 设置请求头信息
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert('http://localhost:3000' + res.data.url)// 文件上传之后的回调，接收服务器响应回来的数据，根据服务器的地址进行填充
          }
        }
      }, // 富文本
      isShowCompile: false, // 编辑弹窗
      rules: {
        title: [
          {
            required: true, message: '该项不能为空', trigger: 'blur'
          }
        ],
        content: [
          {
            required: true, message: '该项不能为空', trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    // 获取表格
    this.getPagesList()
  },
  methods: {
    // 筛选的事件
    async screen() {
      // if (this.input === '') return
      const res = await getPagesList({ title_contains: this.input, _start: this.pagesSetting._start,
        _limit: this.pagesSetting._limit })
      const data2 = await getPagesQuantity({ title_contains: this.input })
      this.total = data2.data.length
      const data = res.data
      this.pagesList = data
      this.currentPage = 0
    },
    // 编辑弹窗确定
    async btnCompileOk() {
      if (this.formData.id) {
        // ==========编辑
        const { content, title, created_at, updated_at } = this.formData
        const id = this.userId
        const data = {
          id,
          content,
          title,
          created_at,
          updated_at
        }
        // 重新拿取富文本的内容
        data.content = this.$refs.vueEditor.editor.root.innerHTML
        await this.$refs.Compile.validate()
        await addCompile(data)
        // =========
      } else {
        // 获取富文本内容
        const quill = this.$refs.vueEditor.editor.root.innerHTML
        // 发起请求
        this.formData.content = quill
        await addPages(this.formData)
      }

      this.$message.success('操作成功')
      this.isShowCompile = false
      // 更新页面
      this.getPagesList()
    },
    // 编辑弹窗取消
    btnCancelCompile() {
      this.isShowCompile = false
      // 清除表单
      this.formData = { title: '', content: '' }
      // 关闭弹窗时清除富文本的内容
      this.$refs.vueEditor.editor.deleteText(0, 9999)
    },
    // 编辑功能
    async pageCompile(id) {
      this.isShowCompile = true
      // 回显数据
      const res = await getCompile(id)
      this.formData = res.data
      this.userId = id
      // 获取富文本内容
      // this.$nextTick(() => {
      const quill = this.$refs.vueEditor.editor
      quill.clipboard.dangerouslyPasteHTML(0, res.data.content)
      // this.formData = { ...this.formData, ...quill }
      // })
    },
    // 删除事件
    async delPages(id) {
      try {
        // 二次询问
        await this.$confirm('是否确认删除?')
        // 发送请求
        await delPages(id)
        // 提示用户
        this.$message.success('删除成功')
        // 更新页面
        this.getPagesList()
      } catch (err) {
        console.log(err)
      }
    },
    // 翻页功能
    async currentChange(newPage) {
      if (this.input !== '') {
        this.currentPage = newPage
        this.pagesSetting._start = (newPage - 1) * this.pagesSetting._limit
        const res = await getPagesQuantity({ title_contains: this.input, ...this.pagesSetting })
        this.pagesList = res.data
        return
      }

      this.currentPage = newPage
      this.pagesSetting._start = (newPage - 1) * this.pagesSetting._limit
      this.getPagesList()
    },
    async getPagesList() {
      const res = await getPagesList(this.pagesSetting)
      this.pagesList = res.data
      const { data } = await getPagesQuantity()
      this.total = data.length
    },
    // 添加页面事件
    addFn() {
      this.isShowCompile = true
    }
  }
}
</script>

<style lang="less" scoped>

</style>
